﻿using MovingChame.WindowsStoreApp.UIModule;
using MovingChameLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Search;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace MovingChame.WindowsStoreApp.Helpers
{
    public static class SearchPaneHelper
    {
        public static Frame Frame { get; set; }

        public static void DeactivateSearchPane()
        {
            SearchPane searchPane;
            searchPane = SearchPane.GetForCurrentView();
            searchPane.PlaceholderText = "Tour name or location name.";
            searchPane.ShowOnKeyboardInput = false;
            searchPane.SuggestionsRequested -= new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(SearchPaneHelper.OnSearchPaneSuggestionsRequested);
            searchPane.QuerySubmitted -= new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
        }

        public static void ActivateSearchPane()
        {
            SearchPane searchPane;
            searchPane = SearchPane.GetForCurrentView();
            searchPane.ShowOnKeyboardInput = true;
            searchPane.SuggestionsRequested += new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(SearchPaneHelper.OnSearchPaneSuggestionsRequested);
            searchPane.QuerySubmitted += new TypedEventHandler<SearchPane, SearchPaneQuerySubmittedEventArgs>(OnQuerySubmitted);
        }

        private static void OnQuerySubmitted(object sender, SearchPaneQuerySubmittedEventArgs args)
        {
            if (!string.IsNullOrEmpty(args.QueryText))
                if (!Frame.Navigate(typeof(SearchResultsPage), args.QueryText))
                    throw new Exception("Failed to create search page");
        }

        public static void OnSearchPaneSuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs e)
        {
            var queryText = e.QueryText;
            if (!string.IsNullOrEmpty(queryText))
            {
                var request = e.Request;
                foreach (string suggestion in Constants.SearchSuggestionList)
                {
                    if (suggestion.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Add suggestion to Search Pane
                        request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);

                        // Break since the Search Pane can show at most 5 suggestions
                        if (request.SearchSuggestionCollection.Size >= Constants.SearchPaneMaxSuggestions)
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
}